package com.feng.fengmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.feng.fengmall.cart.feign.ProductFeignService;
import com.feng.fengmall.cart.interceptor.CartInterceptor;
import com.feng.fengmall.cart.service.CartService;
import com.feng.fengmall.cart.vo.Cart;
import com.feng.fengmall.cart.vo.CartItem;
import com.feng.fengmall.cart.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PATH="fengmall:cart:";

    /**
     * 添加商品信息到购物车Redis中
     * 1、购物车中无此商品
     * 2、购物车中有此商品，加数量
     * @param skuId，商品skuId，标识唯一商品
     * @param num，加购数量
     * @param userId，用户id，标识唯一购物车
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public CartItem addToCart(Long skuId, Integer num, Long userId) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);

        CartItem result = new CartItem();

        String res = (String) redisCart.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                //远程调用product服务，获取sku基本信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo1 = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                result.setCheck(true);
                result.setCount(num);
                result.setSkuId(skuId);
                result.setTitle(skuInfo1.getSkuTitle());
                result.setPrice(skuInfo1.getPrice());
                result.setImage(skuInfo1.getSkuDefaultImg());
            }, executor);

            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
                //远程调用，获取sku对应的属性
                List<String> skuAttr = productFeignService.getSkuSaleAttrValues(skuId);
                result.setSkuAttr(skuAttr);
            }, executor);
            //阻塞等待两个异步线程都执行完
            CompletableFuture.allOf(future,future1).get();

            String s = JSON.toJSONString(result);
            //存到Redis中
            redisCart.put(skuId.toString(),s);
            return result;
        }else {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(num+cartItem.getCount());
            redisCart.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 到Redis中取出加购商品信息
     *
     * @param userId
     * @param skuId
     * @return
     */
    @Override
    public CartItem addCartSuccess(Long skuId, Long userId) {
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);
        CartItem cartItem = JSON.parseObject((String) redisCart.get(skuId.toString()), CartItem.class);
        return cartItem;
    }

    /**
     * 获取购物车
     * @param userId
     * @return
     */
    @Override
    public Cart getCart(Long userId) {
        Cart cart = new Cart();
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);

        List<Object> values = redisCart.values();
        if(values!=null && values.size()>0) {
            List<CartItem> collect = values.stream().map((item) -> {
                String s = item.toString();
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            cart.setItems(collect);
        }

        return cart;
    }

    @Override
    public void checkItem(Long userId, Long skuId, int check) {
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);
        String o = (String) redisCart.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        cartItem.setCheck(check==1);

        String s = JSON.toJSONString(cartItem);
        redisCart.put(skuId.toString(),s);
    }

    /**
     * 增减购物车商品数量
     * @param userId
     * @param skuId
     * @param num
     */
    @Override
    public void countItem(Long userId, Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);
        String o = (String) redisCart.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        cartItem.setCount(num);

        String s = JSON.toJSONString(cartItem);
        redisCart.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long userId, Long skuId) {
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);
        redisCart.delete(skuId.toString());
    }

    @Override
    public void deleteOrderCartItem(List<Long> skuId) {
        MemberRespVo memberRespVo = CartInterceptor.loginUser.get();
        Long userid=memberRespVo.getId();
        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userid);
        for (Long aLong : skuId) {
            redisCart.delete(aLong.toString());
        }
    }

    /**
     * 获取memberId用户的选中购物车信息
     * @param userId
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems(Long userId) {
        MemberRespVo memberRespVo = CartInterceptor.loginUser.get();
        System.out.println(memberRespVo);

        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);
        List<Object> values = redisCart.values();

        if(values!=null && values.size()>0) {
            List<CartItem> collect = values.stream().map((item) -> {
                String s = item.toString();
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                return cartItem;
//                //TODO 这里没有去商品数据库获取最新价格
            }).filter(item->item.getCheck()).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    @Override
    public List<CartItem> getUserCartItems2() {
        MemberRespVo memberRespVo = CartInterceptor.loginUser.get();
        System.out.println(memberRespVo);
        Long userId=memberRespVo.getId();

        BoundHashOperations<String, Object, Object> redisCart = getRedisCart(userId);
        List<Object> values = redisCart.values();
        if(values!=null && values.size()>0) {
            List<CartItem> collect = values.stream().map((item) -> {
                String s = item.toString();
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                //TODO 这里没有去商品数据库获取最新价格
                if (cartItem.getCheck()==true){
                    return cartItem;
                }
                return null;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }



    /**
     * 获取我们要操作的redis购物车
     * @param userId
     * @return
     */
    private BoundHashOperations<String, Object, Object> getRedisCart(Long userId) {
        return redisTemplate.boundHashOps(CART_PATH+userId);
    }

}
